class Wallet < ApplicationRecord
  belongs_to :company, optional: true
  has_many :records, class_name: 'WalletTransLog'

  def timetables_provisionals
    if online
      if store_id.blank?
        slaver_stores = Wallet.where(company_id: company_id, online: true).map(&:store_id).flatten.uniq
        Timetables::Provisional.where(store_id: Store.where(company_id: company_id).pluck(:id) - slaver_stores)
      else
        Timetables::Provisional.where(store_id: store_id)
      end
    else
      Timetables::Provisional.where(store_id: [])
    end
  end

  validate do
    if online
      if try(:store_id).blank?
        raise '子账户下门店不能为空' if Wallet.where("cardinality(store_id) = 0 AND company_id=? AND id != ? AND online = 't'", try(:company_id), id).exists?
      elsif Wallet.where("(store_id && ?) = 't' AND online = 't' AND id != ? ", "{#{store_id.compact.join(',')}}", id).exists?
        raise '管理门店已加入其他账户'
      end
    end
  end
end
